package com.sxbbc.common.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.exceptions.ThrowPageException;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.SysMenus;
import com.sxbbc.common.core.entity.jz.SysRoles;
import com.sxbbc.common.core.mapper.jz.SysMenusMapper;
import com.sxbbc.common.core.mapper.jz.SysRolesMapper;
import com.sxbbc.common.core.service.ISysRolesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author leehao
 * @since 2019-04-27
 */
@Service
public class SysRolesServiceImpl extends ServiceImpl<SysRolesMapper, SysRoles> implements ISysRolesService {

    @Autowired
    private SysMenusMapper sysMenusMapper;

    @Override
    public List<SysMenus> queryMenusByRoleId(Integer id) {
        String menuIds = "";
        if (id != null) {
            SysRoles role = super.getById(id);
            if (role == null) {
                throw new ThrowPageException("未找到角色信息");
            }
            menuIds = "," + role.getMenuIds() + ",";
        }
        QueryWrapper<SysMenus> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StaticUtils.STATUS_YES);
        wrapper.orderByAsc("id,type");
        List<SysMenus> list = sysMenusMapper.selectList(wrapper);
        for (SysMenus l : list) {
            if (StringUtils.isNotBlank(menuIds)) {
                String m = "," + l.getId() + ",";
                if (menuIds.indexOf(m) > -1) {
                    l.setCheck("checked");
                }
            }
        }
        return list;
    }

    @Override
    public RestResponse handleRoleStatus(Integer id, Integer status) {
        SysRoles role = super.getById(id);
        if (role == null) {
            return GetRest.getFail("角色信息异常，请刷新重试");
        }
        role.setStatus(status);
        boolean save = super.updateById(role);
        if (!save) {
            throw new ThrowJsonException("更改角色状态失败");
        }
        return GetRest.getSuccess("操作成功");
    }
}
